/**
 * 模型融合配置表前端管理JS
 */

// API基础路径
let aapModelInfoAPI_BASE = '/api/feibiao/aap/modelinfo';


document.addEventListener('DOMContentLoaded', function() {
    if (typeof API_BASE !== 'undefined') {
        aapModelInfoAPI_BASE = `${API_BASE}/feibiao/aap/modelinfo`;
    }
});

/**
 * 加载模型融合配置表列表
 */
function loadAapModelInfoList(page = 0, size = 10, sort = 'id,asc') {
    currentPage = page;
    pageSize = size;
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';

    fetch(`${aapModelInfoAPI_BASE}/list?page=${page}&size=${size}&sort=${sort}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderAapModelInfoTable(data);
        })
        .catch(error => {
            console.error('获取数据失败:', error);
            mainContent.innerHTML = `<div class="error-container">加载失败: ${error.message}</div>`;
            showMessage('获取模型融合配置失败: ' + error.message, 'error');
        });
}

/**
 * 渲染模型融合配置表
 * @param {Object} data - 分页数据
 */
function renderAapModelInfoTable(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">模型融合配置表</h2>
            <button class="btn btn-primary" onclick="showAapModelInfoForm()">新增</button>
        </div>
        <div class="search-box">
            <input type="text" class="search-input" id="searchInput" placeholder="输入关键词搜索...">
            <button class="search-btn" onclick="searchAapModelInfo()">搜索</button>
        </div>
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>物理模型权重</th>
                    <th>大语言模型权重</th>
                    <th>融合方法</th>
                    <th>关键贡献因素</th>
                    <th>特征重要性</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            html += `
                <tr>
                    <td>${item.id || ''}</td>
                    <td>${item.physicalModelWeight || ''}</td>
                    <td>${item.llmModelWeight || ''}</td>
                    <td>${item.fusionMethod || ''}</td>
                    <td>${formatJsonDisplay(item.keyContributingFactors) || ''}</td>
                    <td>${formatJsonDisplay(item.featureImportance) || ''}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewAapModelInfo(${item.id})">查看</a>
                        <a href="javascript:void(0)" onclick="editAapModelInfo(${item.id})">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteAapModelInfo(${item.id})">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += '<tr><td colspan="7" style="text-align:center;">暂无数据</td></tr>';
    }
    html += `
            </tbody>
        </table>
    `;
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${currentPage <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentPage <= 0 ? 'void(0)' : 'gotoPage(' + (currentPage - 1) + ')'}">上一页</a>
                </li>
        `;
        for (let i = 0; i < data.totalPages; i++) {
            if (i === currentPage) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="gotoPage(${i})">${i + 1}</a></li>`;
            }
        }
        html += `
                <li class="${currentPage >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentPage >= data.totalPages - 1 ? 'void(0)' : 'gotoPage(' + (currentPage + 1) + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    mainContent.innerHTML = html;
}

/**
 * 格式化JSON显示
 * @param {string|Object} json - JSON字符串或对象
 * @returns {string} 格式化后的字符串
 */
function formatJsonDisplay(json) {
    if (!json) return '';
    try {
        const obj = typeof json === 'string' ? JSON.parse(json) : json;
        return JSON.stringify(obj, null, 2);
    } catch (e) {
        return json;
    }
}

/**
 * 跳转到指定页码
 * @param {number} page - 页码
 */
function gotoPage(page) {
    currentPage = page;
    loadAapModelInfoList();
}

/**
 * 搜索模型融合配置表
 */
function searchAapModelInfo() {
    const keyword = document.getElementById('searchInput').value.trim();
    currentPage = 0;
    let url = `${aapModelInfoAPI_BASE}/search?page=${currentPage}&size=${pageSize}`;
    if (keyword) {
        url += `&keyword=${encodeURIComponent(keyword)}`;
    }
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderAapModelInfoTable(data);
        })
        .catch(error => {
            console.error('搜索失败:', error);
            showMessage('搜索失败: ' + error.message, 'error');
        });
}

/**
 * 显示模型融合配置表表单(新增/编辑)
 * @param {Object} data - 已有数据(编辑时传入)
 */
function showAapModelInfoForm(data = null) {
    const mainContent = document.getElementById('mainContent');
    const isEdit = data !== null;
    let html = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}模型融合配置</h2>
            <button class="btn btn-default" onclick="loadAapModelInfoList()">返回列表</button>
        </div>
        <form id="aapModelInfoForm" class="data-form">
            ${isEdit ? `<input type="hidden" name="id" value="${data.id}">` : ''}
            <div class="form-group">
                <label for="physicalModelWeight">物理模型权重 <span class="required">*</span></label>
                <input type="number" id="physicalModelWeight" name="physicalModelWeight" class="form-control" 
                    step="0.0001" min="0" max="1" 
                    value="${isEdit && data.physicalModelWeight ? data.physicalModelWeight : ''}" 
                    required>
            </div>
            <div class="form-group">
                <label for="llmModelWeight">大语言模型权重 <span class="required">*</span></label>
                <input type="number" id="llmModelWeight" name="llmModelWeight" class="form-control" 
                    step="0.0001" min="0" max="1" 
                    value="${isEdit && data.llmModelWeight ? data.llmModelWeight : ''}" 
                    required>
            </div>
            <div class="form-group">
                <label for="fusionMethod">融合方法 <span class="required">*</span></label>
                <select id="fusionMethod" name="fusionMethod" class="form-control" required>
                    <option value="">-- 请选择 --</option>
                    <option value="加权平均" ${isEdit && data.fusionMethod === '加权平均' ? 'selected' : ''}>加权平均</option>
                    <option value="投票法" ${isEdit && data.fusionMethod === '投票法' ? 'selected' : ''}>投票法</option>
                    <option value="堆叠法" ${isEdit && data.fusionMethod === '堆叠法' ? 'selected' : ''}>堆叠法</option>
                </select>
            </div>
            <div class="form-group">
                <label for="keyContributingFactors">关键贡献因素 <span class="required">*</span></label>
                <textarea id="keyContributingFactors" name="keyContributingFactors" class="form-control" required 
                    placeholder="请输入5个关键贡献因素，格式为JSON数组">${isEdit && data.keyContributingFactors ? 
                    (typeof data.keyContributingFactors === 'string' ? data.keyContributingFactors : 
                    JSON.stringify(data.keyContributingFactors, null, 2)) : ''}</textarea>
            </div>
            <div class="form-group">
                <label for="featureImportance">特征重要性 <span class="required">*</span></label>
                <textarea id="featureImportance" name="featureImportance" class="form-control" required 
                    placeholder="请输入特征重要性得分，格式为JSON对象">${isEdit && data.featureImportance ? 
                    (typeof data.featureImportance === 'string' ? data.featureImportance : 
                    JSON.stringify(data.featureImportance, null, 2)) : ''}</textarea>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-default" onclick="loadAapModelInfoList()">取消</button>
            </div>
        </form>
    `;
    mainContent.innerHTML = html;
    document.getElementById('aapModelInfoForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveAapModelInfo(this, isEdit);
    });
}

/**
 * 保存模型融合配置表数据
 * @param {HTMLFormElement} form - 表单元素
 * @param {boolean} isEdit - 是否为编辑模式
 */
function saveAapModelInfo(form, isEdit) {
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    const formData = new FormData(form);
    const data = {};
    formData.forEach((value, key) => {
        if (key === 'keyContributingFactors' || key === 'featureImportance') {
            try {
                data[key] = JSON.parse(value);
            } catch (e) {
                showMessage('JSON格式错误: ' + e.message, 'error');
                return;
            }
        } else {
            data[key] = value;
        }
    });
    if (data.physicalModelWeight) data.physicalModelWeight = parseFloat(data.physicalModelWeight);
    if (data.llmModelWeight) data.llmModelWeight = parseFloat(data.llmModelWeight);
    const url = isEdit ? `${aapModelInfoAPI_BASE}/${data.id}` : `${aapModelInfoAPI_BASE}`;
    const method = isEdit ? 'PUT' : 'POST';
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(text);
            });
        }
        return response.json();
    })
    .then(result => {
        showMessage(`模型融合配置${isEdit ? '更新' : '添加'}成功!`, 'success');
        loadAapModelInfoList();
    })
    .catch(error => {
        console.error('保存失败:', error);
        showMessage(`保存失败: ${error.message}`, 'error');
    });
}

/**
 * 查看模型融合配置表详情
 * @param {number} id - 记录ID
 */
function viewAapModelInfo(id) {
    fetch(`${aapModelInfoAPI_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            showAapModelInfoDetail(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

/**
 * 显示模型融合配置表详情
 * @param {Object} data - 详情数据
 */
function showAapModelInfoDetail(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">模型融合配置详情</h2>
            <button class="btn btn-default" onclick="loadAapModelInfoList()">返回列表</button>
        </div>
        <div class="data-detail">
            <div class="detail-group">
                <label>ID:</label>
                <div>${data.id || '--'}</div>
            </div>
            <div class="detail-group">
                <label>物理模型权重:</label>
                <div>${data.physicalModelWeight || '--'}</div>
            </div>
            <div class="detail-group">
                <label>大语言模型权重:</label>
                <div>${data.llmModelWeight || '--'}</div>
            </div>
            <div class="detail-group">
                <label>融合方法:</label>
                <div>${data.fusionMethod || '--'}</div>
            </div>
            <div class="detail-group">
                <label>关键贡献因素:</label>
                <div><pre>${formatJsonDisplay(data.keyContributingFactors) || '--'}</pre></div>
            </div>
            <div class="detail-group">
                <label>特征重要性:</label>
                <div><pre>${formatJsonDisplay(data.featureImportance) || '--'}</pre></div>
            </div>
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editAapModelInfo(${data.id})">编辑</button>
                <button class="btn btn-danger" onclick="deleteAapModelInfo(${data.id})">删除</button>
                <button class="btn btn-default" onclick="loadAapModelInfoList()">返回</button>
            </div>
        </div>
    `;
    mainContent.innerHTML = html;
}

/**
 * 编辑模型融合配置表
 * @param {number} id - 记录ID
 */
function editAapModelInfo(id) {
    fetch(`${aapModelInfoAPI_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            showAapModelInfoForm(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

/**
 * 删除模型融合配置表
 * @param {number} id - 记录ID
 */
function deleteAapModelInfo(id) {
    if (!confirm('确定要删除这条记录吗？此操作不可恢复!')) {
        return;
    }
    fetch(`${aapModelInfoAPI_BASE}/${id}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(text);
            });
        }
        showMessage('删除成功!', 'success');
        loadAapModelInfoList();
    })
    .catch(error => {
        console.error('删除失败:', error);
        showMessage('删除失败: ' + error.message, 'error');
    });
}

/**
 * 显示消息提示
 * @param {string} msg - 消息内容
 * @param {string} type - 消息类型：success, error, warn, info
 */
function showMessage(msg, type) {
    // 检查是否有全局的 showMessage 函数
    if (typeof window.showMessage === 'function' && window.showMessage !== showMessage) {
        window.showMessage(msg, type);
    } else {
        // 如果没有全局函数，使用简单的 alert
        alert(msg);
    }
} 